package com.jinke.api.modules.api.controller;


import com.jinke.api.modules.app.config.OssConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

/**
 * <p>
 * 承运商平台 前端控制器
 * </p>
 *
 * @author macro
 * @since 2024-01-15
 */

@Controller
@RequestMapping("/api")
@Slf4j
public class ResController {
    @Autowired
    private OssConfig cfg;

    /*
        pdf预览打印
     */
    @GetMapping("/label/printLabel")
    public void previewPdf(HttpServletResponse response, String objectId) throws IOException {
        // todo 判断文件是否被取消


        // PDF文件的URL
        String pdfUrl = cfg.getCdn() + "/pdf/" + objectId + ".pdf";

        // 设置响应头，让浏览器直接显示PDF文件
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "inline; filename=preview.pdf");

        // 从URL获取PDF文件流并写入响应
        try (InputStream inputStream = new URL(pdfUrl).openStream()) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                response.getOutputStream().write(buffer, 0, bytesRead);
            }
        }
    }

}

